package com.hzsai.web.servlet;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hzsai
 * @date 2020/2/20 22:33
 * @usage:
 */
// 添加@WebServlet注解
@WebServlet(urlPatterns = "/my/async_servlet", asyncSupported = true)
public class MyAsyncServlet extends HttpServlet {

    // 覆写方法
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        AsyncContext context = req.startAsync();
//        AsyncContext context = req.getAsyncContext();
        context.start(new Runnable() {
            @Override
            public void run() {
                try {
                    resp.getWriter().println("Hello, AsyncServlet");
                    // 触发完成
                    context.complete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
